package io.kiki.sba.registry.util;

import com.google.common.base.Splitter;
import org.apache.commons.lang.StringUtils;

import java.util.*;
import java.util.Map.Entry;


public class PropertySplitter {


    /**
     * Example: property=KEY1:VALUE1.1,VALUE1.2|KEY2:VALUE2.1,VALUE2.2, defaultKey=ignored
     * Example: property = KEY1:VALUE1.1,VALUE1.2, defaultKey=KEY2
     * Example: property = VALUE1.1,VALUE1.2, defaultKey=KEY2
     *
     * @param defaultKey defaultKey
     * @param property   property
     * @return Map Map
     */
    public Map<String, List<String>> mapOfKeyList(String defaultKey, String property) {
        if (StringUtils.isBlank(property)) {
            return Collections.emptyMap();
        }
        if (StringUtils.contains(property, '|')) {
            return mapOfList(property);
        }
        if (StringUtils.contains(property, ':')) {
            Map<String, List<String>> singleMap = mapOfList(property);
            return Collections.singletonMap(defaultKey, singleMap.values().stream().findFirst().get());
        }
        return Collections.singletonMap(defaultKey, list(property));
    }

    /**
     * Example: one.example.property = KEY1:VALUE1.1,VALUE1.2|KEY2:VALUE2.1,VALUE2.2
     */
    private Map<String, List<String>> mapOfList(String property) {
        if (property == null) {
            return new HashMap<>();
        }
        Map<String, String> map = this.map(property, "|", ":");
        Map<String, List<String>> mapOfList = new HashMap<>();
        for (Entry<String, String> entry : map.entrySet()) {
            mapOfList.put(entry.getKey(), this.list(entry.getValue()));
        }

        return mapOfList;
    }

    /**
     * Example: one.example.property = KEY1:VALUE1,KEY2:VALUE2
     */
    private Map<String, String> map(String property, String splitter, String keyValueSeparator) {
        return Splitter.on(splitter).omitEmptyStrings().trimResults().withKeyValueSeparator(keyValueSeparator).split(property);
    }

    /**
     * Example: one.example.property = VALUE1,VALUE2,VALUE3,VALUE4
     */
    public List<String> list(String property) {
        if (property == null) {
            return new ArrayList<>();
        }
        return this.list(property, ",");
    }

    private List<String> list(String property, String splitter) {
        return Splitter.on(splitter).omitEmptyStrings().trimResults().splitToList(property);
    }


}
